package com.taskflow.controller;

import com.taskflow.common.PageResult;
import com.taskflow.common.Result;
import com.taskflow.dto.TaskQueryDTO;
import com.taskflow.entity.DownloadTask;
import com.taskflow.service.DownloadTaskService;
import com.taskflow.service.TaskSchedulerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 下载任务Controller
 */
@RestController
@RequestMapping("/task")
@CrossOrigin
public class DownloadTaskController {

    @Autowired
    private DownloadTaskService taskService;

    @Autowired
    private TaskSchedulerService schedulerService;

    /**
     * 创建任务
     */
    @PostMapping
    public Result<Long> createTask(@Valid @RequestBody DownloadTask task) {
        try {
            Long id = taskService.createTask(task);
            return Result.success("任务创建成功", id);
        } catch (Exception e) {
            return Result.error("任务创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新任务
     */
    @PutMapping
    public Result<Void> updateTask(@Valid @RequestBody DownloadTask task) {
        try {
            taskService.updateTask(task);
            return Result.success("任务更新成功", null);
        } catch (Exception e) {
            return Result.error("任务更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteTask(@PathVariable Long id) {
        try {
            taskService.deleteTask(id);
            return Result.success("任务删除成功", null);
        } catch (Exception e) {
            return Result.error("任务删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/{id}")
    public Result<DownloadTask> getTask(@PathVariable Long id) {
        try {
            DownloadTask task = taskService.getTaskById(id);
            if (task == null) {
                return Result.error("任务不存在");
            }
            return Result.success(task);
        } catch (Exception e) {
            return Result.error("获取任务失败: " + e.getMessage());
        }
    }

    /**
     * 获取任务列表
     */
    @GetMapping("/list")
    public Result<PageResult<DownloadTask>> getTaskList(TaskQueryDTO query) {
        try {
            PageResult<DownloadTask> result = taskService.getTaskList(query);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取任务列表失败: " + e.getMessage());
        }
    }

    /**
     * 启用/禁用任务
     */
    @PutMapping("/{id}/status/{status}")
    public Result<Void> updateTaskStatus(@PathVariable Long id, @PathVariable Integer status) {
        try {
            taskService.updateTaskStatus(id, status);
            return Result.success("任务状态更新成功", null);
        } catch (Exception e) {
            return Result.error("任务状态更新失败: " + e.getMessage());
        }
    }

    /**
     * 手动执行任务
     */
    @PostMapping("/{id}/execute")
    public Result<Void> executeTask(@PathVariable Long id) {
        try {
            schedulerService.executeTask(id);
            return Result.success("任务已触发执行", null);
        } catch (Exception e) {
            return Result.error("任务执行失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有企业税号列表（用于下拉选择）
     */
    @GetMapping("/company-tax-nos")
    public Result<List<Map<String, String>>> getCompanyTaxNos() {
        try {
            List<DownloadTask> allTasks = taskService.getAllTasks();
            // 去重并构建企业税号列表
            List<Map<String, String>> taxNos = allTasks.stream()
                .filter(task -> task.getCompanyTaxNo() != null && !task.getCompanyTaxNo().isEmpty())
                .collect(Collectors.toMap(
                    DownloadTask::getCompanyTaxNo,
                    task -> {
                        Map<String, String> map = new HashMap<>();
                        map.put("taxNo", task.getCompanyTaxNo());
                        map.put("name", task.getCompanyName());
                        return map;
                    },
                    (existing, replacement) -> existing
                ))
                .values()
                .stream()
                .collect(Collectors.toList());
            return Result.success(taxNos);
        } catch (Exception e) {
            return Result.error("获取企业税号列表失败: " + e.getMessage());
        }
    }
}

